package com.blog.service;

import com.blog.dao.NewsMapper;
import com.blog.exception.ServiceException;
import com.blog.model.News;
import com.github.pagehelper.PageHelper;
import org.apache.tomcat.jni.Thread;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Service
public class NewsService {

    @Resource
    protected NewsMapper newsMapper;
    @Resource
    protected CategoryService categoryService;

    @Resource
    private HttpServletResponse response;

    public List<News> findAll(News news){
        if(news.getPage() != null && news.getRows() != null){
            PageHelper.startPage(news.getPage(), news.getRows());
        }
        Example example = new Example(News.class);
        Example.Criteria criteria = example.createCriteria();
        if(news.getTitle() != null && news.getTitle().length() > 1){
            criteria.andLike("title", "%" + news.getTitle() + "%");
        }
        return newsMapper.selectByExample(example);
    }

    public Integer save(News news){
        Integer a = newsMapper.insert(news);
        categoryService.countCategory();
        return a;
    }

    public void editNews(News news){
        newsMapper.updateByPrimaryKeySelective(news);
    }

    public void delete(Integer id){
        try {
            newsMapper.deleteByPrimaryKey(id);
        }catch (Exception e){
            throw new ServiceException("无法删除");
        }
    }

    public News getNews(Integer id){
        return newsMapper.selectByPrimaryKey(id);
    }
}
